<?php
/**
 * Created by PhpStorm.
 * User: 小蛮哼哼哼
 * Email: 243194993@qq.com
 * Date: 2021/10/22
 * Time: 16:01
 * motto: 现在的努力是为了小时候吹过的牛逼！
 */

namespace app\common\business;


use app\common\lib\Show;
use app\common\lib\Status;
use app\common\validate\Appeal as ValObj;
use app\common\model\mysql\Appeal as ModelObj;
use EasyWeChat\Factory;
use think\Exception;
use think\facade\Log;
use think\helper\Str;

class Appeal extends Base
{
    /**
     * @var ValObj
     */
    protected ValObj $valObj;
    /**
     * @var ModelObj
     */
    protected ModelObj $modelObj;

    /**
     *
     */
    public function __construct()
    {
        $this->valObj = new ValObj();
        $this->modelObj = new ModelObj();
    }

    /**
     * @param int $id
     * @return bool
     * @throws Exception
     */
    public function cancelPaymentCom(int $id = 0, string $msg = "")
    {
        //查询订单是否存在
        try {
            $order = $this->getAppealByOrderId($id);
        } catch (\Exception $e) {
            throw new Exception($e->getMessage());
        }
        $this->modelObj->startTrans();
        try {
            (new PlaceOrder())->updateByData($id, [
                "state" => 5,
                "update_time" => time()
            ]);
            if ($order) {
                $update_data = [
                    "state" => 0,
                    "msg" => $msg,
                    "update_time" => time()
                ];
                $res = $order->save($update_data);
            } else {
                $insert_data = [
                    "order_id" => $id,
                    "msg" => $msg,
                    "state" => 0
                ];
                $this->modelObj->insertAdd($insert_data);
            }
            $this->modelObj->commit();
        } catch (\Exception $e) {
            $this->modelObj->rollback();
            Log::error("bus-appeal-cancelPaymentCom:" . $e->getMessage() . " " . $e->getFile() . " " . $e->getLine());
            throw new Exception("修改失败");
        }
        return true;
    }

    /**
     * @param $id
     * @return ModelObj|array|\think\Model|null
     * @throws Exception
     */
    public function getAppealByOrderId($id)
    {
        try {
            $result = $this->modelObj->getAppealByOrderId($id);
        } catch (\Exception $e) {
            throw new Exception("查询错误");
        }
        return $result;
    }

    /**
     * 同意自动退款
     * @param int $id
     * @return bool
     * @throws Exception
     */
    public function setAppealById(int $id = 0)
    {
        //查询订单
        try {
            $order = $this->modelObj->getBaseById($id, '*,order_id as get_order');
        } catch (\Exception $e) {
            throw new Exception("查询错误");
        }
        $this->modelObj->startTrans();
        try {

            $app = Factory::payment(config('wechat.miniPay'));
            $refund_order = date("YmdHis") . Str::random(8);;
            $result = $app->refund->byOutTradeNumber($order['get_order']['order_id'], $refund_order, $order['get_order']['money'] * 100, $order['get_order']['money'] * 100);
            if ($result['return_code'] == "SUCCESS") {
                $update_order = [
                    "status" => Status::mysql_normal,
                    "payStatus" => 2,
                    "refund_time" => time(),
                    "refund_order" => $refund_order,
                    "refund_code" => Show::json_encode($result),
                    "state" => 4
                ];
                (new PlaceOrder())->updateByData($order['order_id'], $update_order);
                $this->modelObj->updateByData($order['id'], [
                    "state" => 1,
                    "update_time" => time()
                ]);
            }
            $this->modelObj->commit();
        } catch (\Exception $e) {
            $this->modelObj->rollback();
            Log::error("bus-appeal-setAppealById:" . $e->getMessage() . " " . $e->getFile() . " " . $e->getLine());
            throw new Exception("操作失败");
        }
        return true;
    }

    /**
     * @param int $id
     * @param string $msg
     * @throws Exception
     */
    public function setAppealOrder(int $id = 0, string $msg = '')
    {
        try {
            $order = $this->getBaseById($id);
        } catch (\Exception $e) {
            throw new Exception("查询失败");
        }
        if (!$order) {
            throw new Exception("订单不存在");
        }
        $this->modelObj->startTrans();
        try {
            $this->updateByData($id, [
                "state_msg" => $msg,
                "state" => 2,
                "update_time" => time()
            ]);
            (new PlaceOrder())->updateByData($order['order_id'], [
                "state" => 6,
                "state_msg" => $msg,
                "update_time" => time()
            ]);
            (new \app\common\model\mysql\Money())->where('order_id', $order['order_id'])
                ->update([
                    "update_time" => time(),
                    "state" => 1
                ]);
            $this->modelObj->commit();
        } catch (\Exception $e) {
            Log::error("bus-appeal-setAppealOrder:" . $e->getMessage() . " " . $e->getFile() . " " . $e->getLine());
            $this->modelObj->rollback();

            throw new Exception("操作失败");
        }
        return true;
    }

}